package com.uiao.stone.common.config;

import com.uiao.stone.common.enums.OrderType;
import com.uiao.stone.service.OrderStrategy;
import com.uiao.stone.service.serviceImpl.OrderStrategyImplA;
import com.uiao.stone.service.serviceImpl.OrderStrategyImplB;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 枚举策略工厂
 * 使用spring ioc注入单例。或者static方法自己实现单例
 * 执行顺序 static => PostConstruct => afterPropertiesSet
 */
@Component
public class StrategyFactory implements InitializingBean {

    private static final Map<OrderType, OrderStrategy> strategies = new HashMap<>();

    @Autowired
    private OrderStrategyImplA orderStrategyImplA;

    @Autowired
    private OrderStrategyImplB orderStrategyImplB;

    /*static {
        System.out.println("static 方法执行 ==>>");
        strategies.put(OrderType.A, new OrderStrategyImplA());
        strategies.put(OrderType.B, new OrderStrategyImplB());
    }*/

    public static OrderStrategy getStrategy(OrderType type) {
        return strategies.get(type);
    }

    @PostConstruct
    public void putMap() {
        System.out.println("PostConstruct 方法执行 ==>>");
        strategies.put(OrderType.A, orderStrategyImplA);
        strategies.put(OrderType.B, orderStrategyImplB);
    }

    @Override
    public void afterPropertiesSet() {
        System.out.println("afterPropertiesSet 方法执行 ==>>");
        /*List<OrderType> orderTypes = OrderType.getAll();
        for (OrderType orderType : orderTypes) {
            strategies.put(orderType, orderStrategyImplA);
        }*/
        strategies.put(OrderType.A, orderStrategyImplA);
        strategies.put(OrderType.B, orderStrategyImplB);
    }

}
